package com.simafei.flow.core.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.simafei.flow.core.common.Condition;
import com.simafei.flow.core.common.Criteria;
import com.simafei.flow.core.common.Criterion;

import java.io.IOException;

/**
 * @author fengpengju
 */
public class ConditionSerializer extends JsonSerializer<Condition> {

    public static final ConditionSerializer INSTANCE = new ConditionSerializer();

    @Override
    public void serialize(Condition condition, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {
        gen.writeStartObject();
        // 根据具体类型写入其他属性
        if (condition instanceof Criterion criterion) {
            gen.writeStringField("type", "Criterion");
            gen.writeStringField("left", criterion.getLeft());
            gen.writeStringField("operator", criterion.getOperator().name());
            gen.writeStringField("right", criterion.getRight());
            gen.writeStringField("rightType", criterion.getRightType().name());
        } else if (condition instanceof Criteria criteria) {
            gen.writeStringField("type", "Criteria");
            gen.writeStringField("conj", criteria.getConj().name());
            gen.writeFieldName("conditions");
            gen.writeStartArray();
            for (Condition cond : criteria.getConditions()) {
                serializerProvider.defaultSerializeValue(cond, gen);
            }
            gen.writeEndArray();
        } else {
            throw new IllegalArgumentException("Unknown Condition type");
        }
        // 对其他Condition实现添加类似的处理...
        gen.writeEndObject();
    }
}
